package wrm.saferJava.javaagent;

import java.lang.annotation.Annotation;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;


import org.objectweb.asm.ClassAdapter;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;

import wrm.saferJava.annotations.state.StateBinding;
import wrm.saferJava.aop.InjectorBinding;
import wrm.saferJava.aop.oval.OvalBinding;
import wrm.saferJava.aop.oval.OvalGuardInjector;
import wrm.saferJava.oval.guard.Guard;
import wrm.saferJava.oval.internal.util.ReflectionUtils;

public class InjectorTrigger implements ClassFileTransformer {

	private InjectorBinding[] registeredInjectors = new InjectorBinding[]{
			new StateBinding(),
			new OvalBinding(),
			
	};
	
	
	@Override
	public byte[] transform(ClassLoader loader, String className,
			Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
			byte[] classfileBuffer) throws IllegalClassFormatException 
	{
		

		ClassReader cr = new ClassReader(classfileBuffer);
		
		ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
		
		
		//for now: add all bound visitors, they have to take care of triggering annotations by themselves
		//chaining all registered visitors
		ClassVisitor cur = cw;
		for(InjectorBinding b : registeredInjectors)
			cur = b.getClassVisitor(cur, loader);
		
		//Expand_Frames makes writer 2 times slower...but its convenient :)
		cr.accept(cur, ClassReader.EXPAND_FRAMES);
		
		return cw.toByteArray();
	}
	
	
	public static void addInMethod(Object o)
	{
		System.out.println("addInMethod called w: " + o);
	}
	
	
	private boolean hasGuardAnnotation(Class<?> clazz)
	{
		for(Annotation a : ReflectionUtils.getAnnotations(clazz, true))
		{
			if (a.annotationType().equals(Guard.class))
				return true;
		}
		return false;
	}

}
